package leetcode

import "math"

func myAtoi(s string) int {
	r := 0
	minus, start := false, true

	for _, v := range s {
		if v == ' ' && start {
			continue
		}
		if v == '+' && start {
			start = false
			continue
		}
		if v == '-' && start {
			start = false
			minus = true
			continue
		}

		if v > '9' || v < '0' {
			break
		}
		start = false
		r = r*10 + int(v-'0')

		if r > math.MaxInt32 {
			break
		}
	}

	if minus {
		r = -r
	}
	if r > math.MaxInt32 {
		return math.MaxInt32
	}
	if r < math.MinInt32 {
		return math.MinInt32
	}

	return r
}
